﻿using Sys.Common;
using Sys.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Sys.Core.Sys
{
    /// <summary>
    /// 设置业务
    /// </summary>
    public class SettingBll : ExampleBase<SysSetting, SettingBll>
    {
        /// <summary>
        /// 根据Tag获取设置
        /// </summary>
        /// <param name="group">分组</param>
        /// <param name="tag">Tag</param>
        /// <returns>结果Setting实体</returns>
        public SysSetting GetByTag(string group, string tag)
        {
            return GetEntity(m => m.Group.Equals(group) && m.Tag.Equals(tag));
        }

        /// <summary>
        /// 根据Tag获取设置内容
        /// </summary>
        /// <param name="group">分组</param>
        /// <param name="tag">Tag</param>
        /// <returns>结果Setting内容</returns>
        public string GetContent(string group, string tag)
        {
            var model = GetByTag(group, tag);

            if (model != null)
            {
                return model.Content;
            }
            else { return string.Empty; }
        }

        /// <summary>
        /// 判断设置是否存在
        /// </summary>
        /// <param name="group">分组</param>
        /// <param name="tag">Tag</param>
        /// <returns>存在结果</returns>
        public bool IsExist(string group, string tag)
        {
            return Entities.Count(m => m.Group.Equals(group) && m.Tag.Equals(tag)) > 0;
        }

        /// <summary>
        /// 写入设置
        /// </summary>
        /// <param name="group">分组</param>
        /// <param name="tag">Tag</param>
        /// <param name="content">设置内容</param>
        /// <returns>受影响行数</returns>
        public int SetSetting(string group, string tag, string content)
        {
            if (IsExist(group, tag))
            {
                var model = GetByTag(group, tag);

                model.Content = content;

                return Update(model);
            }
            else
            {
                var model = new SysSetting();

                model.ID = StringHelper.GetGuid();
                model.Tag = tag;
                model.Group = group;
                model.Content = content;

                return Insert(model);
            }
        }
    }
}
